<template>
	<view class="searchLayout">

		<!-- 顶部搜索栏 -->
		<view class="search">
			<uni-search-bar @confirm="onSearch" @cancel="onClear" @clear="onClear" focus placeholder="搜索"
				v-model="queryParams.keyword">
			</uni-search-bar>
		</view>

		<!-- 仅壁纸列表为空时，进行展示 -->
		<view class="search-panel" v-if="!classList.length">
			<!-- 仅搜索历史记录不为空时，进行展示 -->
			<view class="history" v-if="historySearch.length">
				<view class="topTitle">
					<view class="text">最近搜索</view>
					<view class="icon" @click="removeHistory">
						<uni-icons type="trash" size="25"></uni-icons>
					</view>
				</view>
				<view class="tabs">
					<view class="tab" v-for="tab in historySearch" :key="tab" @click="clickTab(tab)">{{tab}}</view>
				</view>
			</view>

			<view class="recommend">
				<view class="topTitle">
					<view class="text">热门搜索</view>
				</view>
				<view class="tabs">
					<view class="tab" v-for="tab in recommendList" :key="tab" @click="clickTab(tab)">{{tab}}</view>
				</view>
			</view>
		</view>

		<!-- 搜索结果为空时，展示空状态 -->
		<view class="searchResultEmpty" v-if="searchResultEmpty">
			<uv-empty mode="search"></uv-empty>
		</view>

		<!-- 搜索结果不为空时 -->
		<view v-else>
			<view class="list">
				<navigator :url="`/pages/preview/preview?id=${item._id}`" class="item" v-for="item in classList"
					:key="item._id">
					<image :src="item.smallPicurl" mode="aspectFill"></image>
				</navigator>
			</view>
			<!--  没有更多数据 或者 classList.length不为0时进行展示 -->
			<view class="loadingLayout" v-if="noMore || classList.length"><uni-load-more
					:status="noMore ? 'noMore' : 'loading'" />
			</view>
		</view>


	</view>
</template>

<script setup>
	import {
		ref, watch
	} from "vue";
	import {
		onLoad,
		onUnload,
		onShow,
		onReachBottom
	} from "@dcloudio/uni-app";
	import {
		IMAGES_BY_CATEGORY_STORAGE,
		SEARCH_HISTORY_RECORDS
	} from "@/common/constants/storage";
	import {
		apiSearchWallpaper
	} from "@/api/apis";
import { stringIsEmptyOrBlank } from "@/utils/stringUtil";

	//查询参数
	const queryParams = ref({
		pageNum: 1,
		pageSize: 12,
		keyword: ""
	})

	//搜索历史词
	const historySearch = ref(uni.getStorageSync(SEARCH_HISTORY_RECORDS) || []);

	//热门搜索词
	const recommendList = ref(["美女", "帅哥", "宠物", "卡通"]);

	//没有更多
	const noMore = ref(false);

	//没有搜索结果
	const searchResultEmpty = ref(false);

	//搜索结果列表
	const classList = ref([
		// {_id:123123,smallPicurl:'https://mp-0cb878b7-99ec-44ea-8246-12b123304b05.cdn.bspapp.com/xxmBizhi/20231102/1698905562410_0_small.webp'}
	])
	
	onShow(() => {
		
	})
	
	//页面销毁时，自动执行此函数
	onUnload(() => {
		uni.removeStorageSync(IMAGES_BY_CATEGORY_STORAGE)
	})
	
	watch(() => queryParams.value.keyword, (newValue) => {

		// 当关键字
		if(stringIsEmptyOrBlank(newValue)) {
			onClear()
		}
	})

	//确认搜索之后，执行此函数
	const onSearch = () => {
		if(stringIsEmptyOrBlank(queryParams.value.keyword)) return 
		
		updateSearchHistoryRecords()
		 
		// 根据关键字获取壁纸数据
		getWallpaperByKeyWord()
	}

	const updateSearchHistoryRecords = () => {
		// 更新搜索历史记录, 需借助Set类进行去重
		if (historySearch.value.length === 10) {
			// 获取 [0, 9) 的字符串
			historySearch.value = historySearch.value.slice(0, 9)
		}
		historySearch.value = 
		[...new Set([queryParams.value.keyword, ...historySearch.value])]

		// 将历史记录同步到本地缓存中
		uni.setStorageSync(SEARCH_HISTORY_RECORDS, historySearch.value)
		console.log('queryParams.keyword', queryParams.value.keyword)
	}

	// 获取壁纸
	const getWallpaperByKeyWord = async () => {
		let {
			data
		} = await apiSearchWallpaper(queryParams.value)

		// 页大小 大于 搜索结果的个数时，意味着这是最后一页了
		if (queryParams.value.pageSize > data.length) {
			noMore.value = true
			if (data.length === 0) {
				// 这是最后一页 且 原始列表也无元素时，搜索结果空字段为true
				searchResultEmpty.value = true
			}
		}
		// 进行拼接
		classList.value = classList.value.concat(data)
		
		// 将壁纸列表存到本地缓存中
		uni.setStorageSync(IMAGES_BY_CATEGORY_STORAGE, classList.value)
	}

	//点击清除按钮
	const onClear = () => {
		resetPageData()
	}

	//点击标签进行搜索
	const clickTab = (value) => {
		// 先重置页面数据
		resetPageData()

		queryParams.value.keyword = value

		// 执行搜索
		onSearch()
	}

	const resetPageData = () => {
		queryParams.value.pageNum = 1
		queryParams.value.pageSize = 12
		queryParams.value.keyword = ''
		classList.value = []
		searchResultEmpty.value = false
		noMore.value = false
	}


	//点击清空搜索记录
	const removeHistory = () => {
		uni.showModal({
			title: "是否清空历史搜索？",
			success: res => {
				if (res.confirm) {
					uni.removeStorageSync(SEARCH_HISTORY_RECORDS)
				}
			}
		})
	}

	//触底加载更多
	onReachBottom(() => {

		if (noMore.value) return // 若没有更多数据时，不再进行加载

		queryParams.value.pageNum++
		getWallpaperByKeyWord()


	})

</script>

<style lang="scss" scoped>
	.searchLayout {
		.search {
			padding: 0 10rpx;
		}

		.topTitle {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 32rpx;
			color: #999;
		}

		.history {
			padding: 30rpx;
		}

		.recommend {
			padding: 30rpx;
		}

		.tabs {
			display: flex;
			align-items: center;
			flex-wrap: wrap;
			padding-top: 20rpx;

			.tab {
				background: #F4F4F4;
				font-size: 28rpx;
				color: #333;
				padding: 10rpx 28rpx;
				border-radius: 50rpx;
				margin-right: 20rpx;
				margin-top: 20rpx;
			}
		}

		.list {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 5rpx;
			padding: 20rpx 5rpx;

			.item {
				height: 440rpx;

				image {
					width: 100%;
					height: 100%;
					display: block;
				}
			}
		}
	}
</style>